package cn.zf233.jwtshiro.config.shiro.upwd;

import cn.zf233.jwtshiro.entity.User;
import cn.zf233.jwtshiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created by zf233 on 2021/7/12
 */
@Slf4j
public class UPWDRealm extends AuthorizingRealm {

    private final UserService userService;

    public UPWDRealm(UserService userService) {
        this.userService = userService;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();//获取页面中传递的用户账号
        String password = new String(token.getPassword());//获取页面中的用户密码实际工作中基本不需要获取
        log.info("准备验证用户:'{}' (PWD)" + username);
        User result = userService.getUserByUsername(username);
        if (result == null) {
            log.info("用户不存在");
            throw new UnknownAccountException("不存在的用户");
        }
        log.info("用户存在，准备验证密码");
        if (!result.getPassword().equals(password)) {
            log.info("用户信息验证失败，密码有误");
            throw new IncorrectCredentialsException("密码错误");
        }
        log.info("用户信息验证通过");
        return new SimpleAuthenticationInfo(result, password, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
